<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			#canvas{
				display: block;
				margin: 20px auto;
				background-color: #000;
				box-shadow: 0 0 10px rgba(0,0,0,0.5);
			}
		</style>
	</head>
	<body>
		<canvas id="canvas"></canvas>
		<script src="../libs/utils.js"></script>
		<script src="../components/ball.js"></script>
		<script type="text/javascript">
			var canvas = document.querySelector('#canvas')
			var ctx = canvas.getContext('2d');
			
			var w = canvas.width = 500;
			var h = canvas.height = 300
			// 对象池
			var balls = [];
			// 加速度
			var g = 0.05;
			createBall();
			(function move(){
				window.requestAnimationFrame(move)
				ctx.clearRect(0,0,w,h)
				
				var i = balls.length;
				while(i--){
					ballMove(balls[i],i)
				}
				
			})()
			
			// 小球移动
			function ballMove(ball,index){
				ball.x +=ball.vx;
				ball.y +=ball.vy;
				ball.render(ctx);
				// 物体上升vy是负值，所以当加上加速度vy为正值的时候，物体就会下落。
				ball.vy +=g;
				// 超出边界，重置物体，将物体移动到画布底部中间位置
				if(ball.x-ball.r>=w || ball.x+ball.r<=0 || ball.y-ball.r>=h || ball.y+ball.r<=0){
					ball.x=w/2,
					ball.y=h,
					ball.vx=$C.random([-3,3]),
					ball.vy=$C.random([0,-10])
				}
			}
			// 创建小球
			function createBall(){
				for(var i=0;i<100;i++){
					balls.push(new Ball({
						x:w/2,
						y:h,
						r:$C.random([5,10],true),
						fillStyle:$C.createColor(),
						//vx,初始速度为负值,物体向左移动，为正值，物体向右移动。
						vx:$C.random([-3,3]),
						// vy初始速度为负值，物体运动上升
						vy:$C.random([0,-10])
					}))
				}
			}
			
		</script>
	</body>
</html>
